import com.google.gson.JsonObject;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

/**
 * @description：一个简单的 HttpServer 的测试
 * @author: yangyahui01
 * @date: 11/27/24 2:53 PM
 */
public class SimpleHttpServer {

    public static void main(String[] args) {

        try {
            HttpServer server = HttpServer.create(new InetSocketAddress(8088), 0);

            server.createContext("/young/schedule/node/register", new MyHandler());


            server.start();

            System.out.println("Server is listening on port 8000...");

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    // 自定义 HttpHandler
    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {

            System.out.println("监听请求.......");

            // 打印请求方法和路径
            System.out.println("Request method: " + exchange.getRequestMethod());
            System.out.println("Request URI: " + exchange.getRequestURI());


            JsonObject jsonObject = new JsonObject();

            jsonObject.addProperty("status", "ok");
            jsonObject.addProperty("code","S00000");


            String response = jsonObject.toString();



            // 发送响应状态码
            exchange.sendResponseHeaders(200, response.length());

            // 发送响应体
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}
